#Clear workspace

rm(list=ls())

in.dir = "C:/R/In/"
out.dir = "C:/R/Out/"

#Set working directory
setwd(in.dir)

#load necessary libraries

#list the libraries needed
necessary=c("adehabitat","SDMTools","quantreg")
#check if library is installed
installed = necessary %in% installed.packages()
#if library is not installed, install it
if (length(necessary[!installed]) >=1) install.packages(necessary[!installed], dep = T)

#load the libraries
for (lib in necessary) library(lib,character.only=T)

#Import the dataset to intersect with the microclimate layer

rawdata= read.csv("residualabundanceplussd.csv",header=T)

#Import the microclimate layer

#t.file = paste(in.dir,"bc_05_buff.asc",sep="")
#t.asc = read.asc(t.file)

#Import the homemade layer

t.file2 = paste(in.dir,"bc05minusbc05buff.asc",sep="")
t.asc2 = read.asc(t.file2)

#Intersect the microclimate layer with the abundance data

east = c(rawdata$east)
north = c(rawdata$north)
pnts = data.frame(east=east, north=north)
#pnts$micro = join.asc(pnts, t.asc)
pnts$micro = join.asc(pnts, t.asc2)
resid.micro = merge(pnts,rawdata,by=c("east","north"))
rm(t.asc)



#Perform OLS Regression between microclimate and residual abundance

lcOLSmicroresid = lm(lcresidabund~micro, data=resid.micro)
gqOLSmicroresid = lm(gqresidabund~micro, data=resid.micro)
crOLSmicroresid = lm(crresidabund~micro, data=resid.micro)
sbOLSmicroresid = lm(sbresidabund~micro, data=resid.micro)

#Create plots of microclimate versus residual abundance and overlay the OLS line

plot(resid.micro$micro, resid.micro$lcresidabund, xlab="micro", ylab="resid", main="LAMCOGG OLS",abline(lcOLSmicroresid, col="red"))
plot(resid.micro$micro, resid.micro$gqresidabund, xlab="micro", ylab="resid", main="GNYQUEE OLS",abline(gqOLSmicroresid, col="red"))
plot(resid.micro$micro, resid.micro$crresidabund, xlab="micro", ylab="resid", main="CARRUBR OLS",abline(crOLSmicroresid, col="red"))
plot(resid.micro$micro, resid.micro$sbresidabund, xlab="micro", ylab="resid", main="SAPBASI OLS",abline(sbOLSmicroresid, col="red"))

#Perform OLS Regression between microclimate and standard deviation of local abundance

lcOLSmicrosd = lm(lcSD~micro, data=resid.micro)
gqOLSmicrosd = lm(gqSD~micro, data=resid.micro)
crOLSmicrosd = lm(crSD~micro, data=resid.micro)
sbOLSmicrosd = lm(sbSD~micro, data=resid.micro)

#Create plots of microclimate versus standard deviation of local abundance and overlay OLS line

plot(resid.micro$micro, resid.micro$lcSD, xlab="micro", ylab="SD", main="LAMCOGG OLS",abline(lcOLSmicrosd, col="red"))
plot(resid.micro$micro, resid.micro$gqSD, xlab="micro", ylab="SD", main="GNYQUEE OLS",abline(gqOLSmicrosd, col="red"))
plot(resid.micro$micro, resid.micro$crSD, xlab="micro", ylab="SD", main="CARRUBR OLS",abline(crOLSmicrosd, col="red"))
plot(resid.micro$micro, resid.micro$sbSD, xlab="micro", ylab="SD", main="SAPBASI OLS",abline(sbOLSmicrosd, col="red"))

hist(resid.micro)